package com.cool.reggie.modules.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cool.reggie.core.redis.RedisUtils;
import com.cool.reggie.modules.user.entity.UserEntity;
import com.cool.reggie.modules.user.form.LoginForm;
import com.cool.reggie.modules.user.service.UserService;
import com.cool.reggie.utils.ResultData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author 1950735817@qq.com
 * @since 2022-07-15
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public ResultData sendMsg(@RequestBody UserEntity user, HttpSession session) {
        String phone = user.getPhone();

        if (StringUtils.isNotBlank(phone)) {
            // 生成手机验证码
            String code = "1234";

            // 调用阿里云服务发送短信。此处暂无

            // 保存手机验证码
//            session.setAttribute(phone, code);
            // 使用redis保存验证按
            redisUtils.set(phone,code, 60*5);

            return ResultData.ok(code);
        }

        return ResultData.error("登录失败");
    }


    /**
     * @param loginForm
     * @param session
     * @return
     */
    @PostMapping("/login")
    public ResultData login(@RequestBody Map loginForm, HttpSession session) {
        String phone = loginForm.get("phone").toString();
        String code = loginForm.get("code").toString();

        // 与发送的手机验证码对比
//        String sessionCode = session.getAttribute(phone).toString();
        String sessionCode = redisUtils.get(phone,String.class);

        if (StringUtils.isBlank(sessionCode) || !sessionCode.equals("1234")) {
            return ResultData.error("登陆失败");
        }

        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getPhone, phone);

        UserEntity userEntity = userService.getOne(queryWrapper);

        // 没有注册则直接保存
        if (userEntity == null) {
            UserEntity newUser = new UserEntity();
            newUser.setPhone(phone);
            newUser.setStatus(1);
            userService.save(newUser);
            session.setAttribute("user",newUser.getId());
            return ResultData.ok("登录成功");
        }

        // 过滤器标识
        session.setAttribute("user",userEntity.getId());

        redisUtils.delete(phone);

        return ResultData.ok(userEntity);
    }

}
